package nickthissen.iracing.adapters;

import java.util.ArrayList;

import nickthissen.iracing.activities.ItemListActivity;
import nickthissen.iracing.datamodels.Forum;
import nickthissen.iracing.iracingforum2.R;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ForumListAdapter extends ArrayAdapter<Forum>
{
	private ItemListActivity<Forum> activity;
	private ArrayList<Forum> items;
		
	public ForumListAdapter(ItemListActivity<Forum> context, int resourceId, ArrayList<Forum> items)
	{
		super(context, resourceId, items);
		this.activity = context;
		this.items = items;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		View v = convertView;
		if (v == null)
		{
			LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.forumrow, null);
		}
		
		Forum forum = items.get(position);
		if (forum != null)
		{
			v.setClickable(true);
			v.setOnClickListener(new ItemClickListener(forum));
			v.setOnCreateContextMenuListener(null);
			
			TextView lblTop = (TextView) v.findViewById(R.id.lblTop);
			LinearLayout background = (LinearLayout) v.findViewById(R.id.background);
			ImageView imgIcon = (ImageView) v.findViewById(R.id.imgIcon);
				
			lblTop.setMaxLines(1);
			
			if (forum.IsCategoryHeader)
			{
				lblTop.setText(forum.Category);								
				lblTop.setTextColor(Color.WHITE);
				background.setBackgroundResource(R.drawable.categorybg);

				lblTop.setTypeface(null, Typeface.BOLD);
				imgIcon.setVisibility(View.GONE);
			}
			else							
			{
				lblTop.setText(forum.Title);							
				lblTop.setTextColor(Color.BLACK);
				background.setBackgroundResource(R.color.rowbgselector);

				lblTop.setTypeface(null, Typeface.NORMAL);
				
				imgIcon.setVisibility(View.VISIBLE);
				imgIcon.setImageResource(getImageId(forum.IconName));
				
			}
		}
		return v;
	}
	
	private Resources resources;
	private String packageName;
	
	private int getImageId(String name)
	{
		if (resources == null) resources = activity.getResources();
		if (packageName == null) packageName = activity.getPackageName();
		
		return resources.getIdentifier(name , "drawable", packageName);
	}
	
	private class ItemClickListener implements View.OnClickListener
	{
		private Forum forum;
		
		public ItemClickListener(Forum f)
		{
			this.forum = f;
		}
		
		@Override
		public void onClick(View v)
		{
			//v.setSelected(true);
			activity.onItemClicked(forum);
		}		
	}
}
